package cn.rebeater.navigationclient.ui.home;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import java.lang.ref.WeakReference;

import cn.rebeater.navigationclient.DeviceListActivity;
import cn.rebeater.navigationclient.R;

import static android.app.Activity.RESULT_OK;


/**
 * Handler 处理方式
 */
class ActivityHandler extends Handler {
    private final WeakReference<HomeFragment> mainactivity;


    ActivityHandler(HomeFragment acticity) {
        mainactivity = new WeakReference<>(acticity);
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        HomeFragment acticity = mainactivity.get();
        if (acticity != null) {
            switch (msg.arg1) {
                case BluetoothMsgType.msgdata: {

                    acticity.homeViewModel.addMessage((String) msg.obj);
                    double[] pvts = new double[32];
                    int i;
                    String[] strings = ((String) msg.obj).split(",");
                    Log.i("mydebug", "handleMessage: receive data length = " + strings.length);
                    try {
                        for( i  =0; i < strings.length-1; i++){
                            pvts[i] = Double.parseDouble(strings[i+1]);
                        }
                        if (strings[0].substring(1).equals ("$POS") && strings.length >= 13) {
                                acticity.sendMessage(HomeFragment.NavMessageType.POS,pvts, 13);
                        }else if(strings[0].equals("$BIAS") && strings.length >= 9){
                            acticity.sendMessage(HomeFragment.NavMessageType.BIAS,pvts, 9);
                        }else if(strings[0].equals("$STD")&& strings.length >= 12){
                            acticity.sendMessage(HomeFragment.NavMessageType.STD,pvts, 12);
                        }

                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case BluetoothMsgType.msgerror: {
                    break;
                }
                case BluetoothMsgType.msginterrupt: {
                    Toast.makeText(acticity.getContext(), "disconnect", Toast.LENGTH_LONG).show();
                    break;
                }
            }
        }

    }
}

public class HomeFragment extends Fragment {

    public HomeViewModel homeViewModel;
    Button btn_tocan;
    Button btn_disconnect;
    TextView tx_message;
    FragmentManager parentFragmentManager;
    ActivityHandler mbthandler;
    private String TAG = "mydebug";
    private int x = 0;
    private BluetoothThread mbtthread = null;
    private BluetoothAdapter mbtadapter = null;
    private int REQUEST_SCAN_BLUETOOTH = 3;
    private ScrollView scol_msg;
    enum NavMessageType{
        POS,
        BIAS,
        STD
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        btn_tocan = root.findViewById(R.id.btn_to_scan);
        btn_disconnect = root.findViewById(R.id.btn_disconnect);
        tx_message = root.findViewById(R.id.tx_messages);
        scol_msg = root.findViewById(R.id.scoll_home);

        mbtadapter = BluetoothAdapter.getDefaultAdapter();

        mbthandler = new ActivityHandler(this);

        btn_tocan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: go to scan");
                if (mbtthread != null) {
                    mbtthread.onDestroy();
//                    mbtthread =null;
                }
                goToScanActivityForResult();

            }
        });

        btn_disconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: disconnect");
                mbtthread.onDestroy();

            }
        });
        homeViewModel.getMessage().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                tx_message.setText(s);
                scol_msg.fullScroll(ScrollView.FOCUS_DOWN);
//                textView.setText(s);
            }
        });
        parentFragmentManager = getParentFragmentManager();
//        parentFragmentManager.setFragmentResultListener();


        return root;
    }

    void sendMessage( NavMessageType type, double[] s, int length) {
        Bundle result = new Bundle();
        result.putDoubleArray("bundleKey", s);
        switch (type){
            case POS:   getParentFragmentManager().setFragmentResult("requestKeyForMap", result);break;
            case BIAS:   getParentFragmentManager().setFragmentResult("requestKeyForBias", result);break;
            case STD:   getParentFragmentManager().setFragmentResult("requestKeyForStd", result);break;
        }


//        getParentFragmentManager().setFragmentResult("requestKeyForChart", result);
    }

    void goToScanActivityForResult() {
        Intent intent = new Intent(getContext(), DeviceListActivity.class);
        startActivityForResult(intent, REQUEST_SCAN_BLUETOOTH);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SCAN_BLUETOOTH) {
            if (resultCode == RESULT_OK) {
                final String[] device = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME).split("\n");
                try {

                    new Thread() {
                        @Override
                        public void run() {
//                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.getDefault());// HH:mm:ss
//获取当前时间
//                            Date date = new Date(System.currentTimeMillis());
//                            logFileName = simpleDateFormat.format(date) + ".log";
//                            logFileName = logPath + File.separator + logFileName;
//                            Log.i(TAG, "run: log file name:" + logFileName);
                            Log.i(TAG, "run: on Activity result");
                            BluetoothDevice btdevice = mbtadapter.getRemoteDevice(device[1]);
                            mbtthread = new BluetoothThread(btdevice, mbthandler, "logFileName");
                            mbtthread.start();

                        }
                    }.start();


                    /* 重新连接，清理轨迹 */
//                    mbaidumap.clear();
                } catch (Exception e) {
//                    disconnect("连接失败");
                }
            } else {
//                txdevice.setText("连接中断");
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.clear_record:

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}